package com.atguigu.tingshu.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.LongTermsAggregate;
import co.elastic.clients.elasticsearch._types.aggregations.LongTermsBucket;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggestOption;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import co.elastic.clients.json.JsonData;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.query.search.AlbumIndexQuery;
import com.atguigu.tingshu.search.repository.AlbumInfoIndexRepository;
import com.atguigu.tingshu.search.repository.SuggestIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.search.AlbumInfoIndexVo;
import com.atguigu.tingshu.vo.search.AlbumSearchResponseVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;


@Slf4j
@Service
@SuppressWarnings({"all"})
public class SearchServiceImpl implements SearchService {

    @Autowired
    private AlbumInfoIndexRepository albumInfoIndexRepository;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private Executor threadPoolTaskExecutor;
    @Autowired
    private ElasticsearchClient elasticsearchClient;
    @Autowired
    private SuggestIndexRepository suggestIndexRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    //专辑索引库名称
    private static final String INDEX_NAME = "albuminfo";

    //专辑自动补全索引库名称
    private static final String SUGGEST_INDEX_NAME = "suggestinfo";
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void upperAlbum(Long albumId) {
        //创建索引库对象
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();

        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //封装索引库专辑信息
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑信息, {}不存在", albumId);
            BeanUtil.copyProperties(albumInfo, albumInfoIndex);
            //标签列表手动处理
            List<AlbumAttributeValue> albumAttributeValueVoList = albumInfo.getAlbumAttributeValueVoList();
            if (CollectionUtil.isNotEmpty(albumAttributeValueVoList)) {
                List<AttributeValueIndex> attributeValueIndexList = albumAttributeValueVoList
                        .stream()
                        .map(albumAttributeValueVo -> BeanUtil.copyProperties(albumAttributeValueVo, AttributeValueIndex.class)
                        ).collect(Collectors.toList());
                albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);
            }
            return albumInfo;
        }, threadPoolTaskExecutor);

        CompletableFuture<Void> categoryCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            //封装索引库分类信息
            BaseCategoryView baseCategoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData();
            Assert.notNull(baseCategoryView, "分类：{}不存在", albumInfoIndex.getCategory3Id());
            albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
            albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
        }, threadPoolTaskExecutor);

        CompletableFuture<Void> userCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            //封装索引库用户信息
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData();
            Assert.notNull(userInfoVo, "用户：{}信息为空", albumInfo.getUserId());
            albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());

        }, threadPoolTaskExecutor);

        CompletableFuture<Void> statCompletableFuture = CompletableFuture.runAsync(() -> {
            //5.封装文档对象中统计相关信息 TODO 采用随机生成方式
            //5.1 封装播放量数值
            int playStatNum = RandomUtil.randomInt(1000, 2000);
            albumInfoIndex.setPlayStatNum(playStatNum);
            //5.2 封装订阅量数值
            int subscribeStatNum = RandomUtil.randomInt(800, 1000);
            albumInfoIndex.setSubscribeStatNum(subscribeStatNum);
            //5.3 封装购买量数值
            int buyStatNum = RandomUtil.randomInt(100, 500);
            albumInfoIndex.setBuyStatNum(buyStatNum);
            //5.4 封装评论量数值
            int commentStatNum = RandomUtil.randomInt(500, 1000);
            albumInfoIndex.setCommentStatNum(commentStatNum);
            //5.5 基于以上生成统计数值计算出当前文档热度分值  热度=累加（不同统计数值*权重）
            BigDecimal bigDecimal1 = new BigDecimal("0.1").multiply(BigDecimal.valueOf(playStatNum));
            BigDecimal bigDecimal2 = new BigDecimal("0.2").multiply(BigDecimal.valueOf(subscribeStatNum));
            BigDecimal bigDecimal3 = new BigDecimal("0.3").multiply(BigDecimal.valueOf(buyStatNum));
            BigDecimal bigDecimal4 = new BigDecimal("0.4").multiply(BigDecimal.valueOf(commentStatNum));
            BigDecimal hotScore = bigDecimal1.add(bigDecimal2).add(bigDecimal3).add(bigDecimal4);
            albumInfoIndex.setHotScore(hotScore.doubleValue());
        }, threadPoolTaskExecutor);
        //组合异步任务
        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                categoryCompletableFuture,
                userCompletableFuture,
                statCompletableFuture
        ).join();

        //将索引库信息保存到索引库
        albumInfoIndexRepository.save(albumInfoIndex);

        //将专辑标题存入提词索引库
        this.saveSuggestIndex(albumInfoIndex);
        //将上架的专辑ID存入布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        bloomFilter.add(albumId);
    }

    /**
     * 将指定专辑下架，从索引库删除文档
     *
     * @param albumId
     * @return
     */
    @Override
    public void lowerAlbum(Long albumId) {

        albumInfoIndexRepository.deleteById(albumId);
        suggestIndexRepository.deleteById(albumId.toString());
    }

    /**
     * 整体采用传统写法，局部采用Lambda表达方式
     * 根据条件检索ElasticSearch专辑索引库
     *
     * @param albumIndexQuery 查询条件
     * @return
     */


    @Override
    public AlbumSearchResponseVo search(AlbumIndexQuery albumIndexQuery) {
        try {
            //构建检索请求对象
            SearchRequest searchRequest = this.buildDSL(albumIndexQuery);
            System.err.println("检索请求：" + searchRequest);
            //调用es客户端执行索引库检索
            SearchResponse<AlbumInfoIndex> albumInfoIndexSearchResponse = elasticsearchClient.search(searchRequest, AlbumInfoIndex.class);
            //解析封装检索结果
            return this.parseSearchResult(albumInfoIndexSearchResponse, albumIndexQuery);
        } catch (IOException e) {
            log.error("[检索服务]站内搜索异常：{}", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 基于检索条件对象封装检索请求对象（封装完整DSL语句）
     *
     * @param albumIndexQuery
     * @return
     */
    @Override
    public SearchRequest buildDSL(AlbumIndexQuery albumIndexQuery) {
        //创建检索请求构建器对象->封装请求路径索引名称及完整的请求体参数
        SearchRequest.Builder builder = new SearchRequest.Builder();
        builder.index(INDEX_NAME);
        //封装请求体参数
        //1. todo 封装查询条件query:关键字、分类、标签
        String keyword = albumIndexQuery.getKeyword();
        //1.1 封装关键字查询条件
        BoolQuery.Builder allConditionBoolQueryBuilder = new BoolQuery.Builder();
        if (StringUtils.isNotBlank(keyword)) {
            allConditionBoolQueryBuilder.must(m -> m.bool(b ->
                    b.should(s -> s.match(m1 -> m1.field("albumTitle").query(keyword)))
                            .should(s -> s.match(m1 -> m1.field("albumIntro").query(keyword)))
                            .should(s -> s.term(t -> t.field("announcerName").value(keyword)))));
        }
        //1.2 封装分类查询条件
        Long category1Id = albumIndexQuery.getCategory1Id();
        if (category1Id != null) {
            allConditionBoolQueryBuilder.filter(f -> f.term(t -> t.field("category1Id").value(category1Id)));
        }
        Long category2Id = albumIndexQuery.getCategory2Id();
        if (category2Id != null) {
            allConditionBoolQueryBuilder.filter(f -> f.term(t -> t.field("category2Id").value(category2Id)));
        }
        Long category3Id = albumIndexQuery.getCategory3Id();
        if (category3Id != null) {
            allConditionBoolQueryBuilder.filter(f -> f.term(t -> t.field("category3Id").value(category3Id)));
            //1.3 封装标签查询条件
            List<String> attributeList = albumIndexQuery.getAttributeList();
            if (CollectionUtil.isNotEmpty(attributeList)) {
                for (String attribute : attributeList) {
                    //2.2.4.1 每循环一次设置一组标签过滤条件 标签ID:标签值ID
                    String[] split = attribute.split(":");
                    if (split != null && split.length == 2) {
                        allConditionBoolQueryBuilder.filter(f -> f.nested(
                                n -> n.path("attributeValueIndexList")
                                        .query(q -> q.bool(
                                                b -> b.must(m -> m.term(t -> t.field("attributeValueIndexList.attributeId").value(split[0])))
                                                        .must(m -> m.term(t -> t.field("attributeValueIndexList.valueId").value(split[1])))
                                        ))
                        ));
                    }
                }
            }
        }
        builder.query(allConditionBoolQueryBuilder.build()._toQuery());
        //2.封装分页条件 from size
        builder.from((albumIndexQuery.getPageNo() - 1) * albumIndexQuery.getPageSize()).size(albumIndexQuery.getPageSize());
        //3.封装排序条件 sort 1:综合排序 2:发布时间排序 3:播放量排序
        String order = albumIndexQuery.getOrder();
        if (StringUtils.isNotBlank(order)) {
            String[] split = order.split(":");
            if (split.length == 2 && split != null) {
                //得到排序字段和排序方式
                String sortField = "";
                switch (split[0]) {
                    case "1":
                        sortField = "hotScore";
                        break;
                    case "2":
                        sortField = "playStatNum";
                        break;
                    case "3":
                        sortField = "createTime";
                        break;
                }
                String finalSortField = sortField;
                builder.sort(s -> s.field(f -> f.field(finalSortField)
                        .order(split[1].equals("desc") ? SortOrder.Desc : SortOrder.Asc)));
            }
        }

        //4.封装高亮条件 highlight
        if (StringUtils.isNotBlank(keyword)) {
            builder.highlight(h -> h.fields("albumTitle", f -> f.preTags("<font style='color:red'>").postTags("</font>")));
        }
        //5.设置文档响应字段
        builder.source(s -> s.filter(f -> f.includes("id", "albumTitle", "albumIntro", "coverUrl", "includeTrackCount", "playStatNum", "createTime", "payType")));

        //基于构建器对象产生检索请求对象
        return builder.build();
    }

    @Override
    public AlbumSearchResponseVo parseSearchResult(SearchResponse<AlbumInfoIndex> searchResponse, AlbumIndexQuery albumIndexQuery) {
//        创建响应vo对象
        AlbumSearchResponseVo vo = new AlbumSearchResponseVo();
        //封装vo中的分页信息
        Integer pageNo = albumIndexQuery.getPageNo();
        Integer pageSize = albumIndexQuery.getPageSize();
        vo.setPageNo(pageNo);
        vo.setPageSize(pageSize);
        //计算总页数
        HitsMetadata<AlbumInfoIndex> hits = searchResponse.hits();
        long total = hits.total().value();
        long totalPage=total%=pageSize==0?total/pageSize:total/pageSize+1;
        vo.setTotal(total);
        vo.setTotalPages(totalPage);
        //封装vo中的业务数据信息
        //1.获取检索对象中hits对象中的hits数组
        List<Hit<AlbumInfoIndex>> hitsList = hits.hits();

        //2.遍历hits数组，得到文档中的_source对应的文档对象
        if (CollUtil.isNotEmpty(hitsList)){
            List<AlbumInfoIndexVo> list = hitsList.stream()
                    .map(hit -> {
                        AlbumInfoIndex albumInfoIndex = hit.source();
                        //3.替换高亮字段
                        Map<String, List<String>> map = hit.highlight();
                        if (CollUtil.isNotEmpty(map)) {
                            List<String> albumTitle = map.get("albumTitle");
                            String highLightTest = albumTitle.get(0);
                            albumInfoIndex.setAlbumTitle(highLightTest);

                        }
                        return BeanUtil.copyProperties(albumInfoIndex, AlbumInfoIndexVo.class);
                    }).collect(Collectors.toList());
            vo.setList(list);
        }




        //响应vo对象
        return vo;
    }

    /**
     * 查询置顶3级分类下热度TOP6专辑列表
     *
     * @param category1Id
     * @return
     */
    @Override
    public List<Map<String, Object>> searchTopCategoryHotAlbum(Long category1Id) {
        try {
            //根据一级分类查询7个置顶的三级分类
            //远程调用专辑服务
            List<BaseCategory3> baseCategory3List = albumFeignClient.getTopBaseCategory3(category1Id).getData();
            Assert.notNull(baseCategory3List, "根据一级分类查询7个置顶的三级分类失败");
            //将三级分类对象转为es检索需要的fieldvalue类型
            List<FieldValue> fieldValueList = baseCategory3List.stream()
                    .map(baseCategory3 -> FieldValue.of(baseCategory3.getId()))
                    .collect(Collectors.toList());

            //将三级分类列表转为map
            Map<Long, BaseCategory3> baseCategory3Map = baseCategory3List.stream()
                    .collect(Collectors.toMap(BaseCategory3::getId, baseCategory3 -> baseCategory3));

            //采用多关键字精确查询+聚合执行检索es
            SearchResponse<AlbumInfoIndex> albumInfoIndexSearchResponse = elasticsearchClient.search(
                    s -> s.index(INDEX_NAME)
                            .size(0)
                            .query(q -> q.terms(t -> t.field("category3Id").terms(t1 -> t1.value(fieldValueList))))
                            .aggregations(
                                    "category_agg", a -> a.terms(t -> t.field("category3Id").size(7))
                                            .aggregations("top6", a1 -> a1.topHits(t -> t.size(6).sort(s1 -> s1.field(f -> f.field("hotScore").order(SortOrder.Desc))).source(s1 -> s1.filter(f -> f.excludes("attributeValueIndexList")))))
                            ),
                    AlbumInfoIndex.class
            );

            //解析响应结果封装置顶分类热门专辑列表
            LongTermsAggregate categoryAgg = albumInfoIndexSearchResponse.aggregations().get("category_agg").lterms();
            List<LongTermsBucket> categoryTermsBucketList = categoryAgg.buckets().array();
            if (CollUtil.isNotEmpty(categoryTermsBucketList)) {
                //每遍历一次，封装置顶分类热门专辑map对象
                List<Map<String, Object>> list = categoryTermsBucketList
                        .stream()
                        .map(categoryBucket -> {
                            Map<String, Object> map = new HashMap<>();
                            //获取桶中三级分类id
                            map.put("baseCategory3", baseCategory3Map.get(categoryBucket.key()));
                            //获取桶中热门专辑列表
                            List<AlbumInfoIndex> top6List = categoryBucket.aggregations().get("top6").topHits().hits().hits()
                                    .stream()
                                    .map(hit -> {
                                        String albumInfoIndexStr = hit.source().toString();
                                        AlbumInfoIndex albumInfoIndex = JSON.parseObject(albumInfoIndexStr, AlbumInfoIndex.class);
                                        return albumInfoIndex;

                                    })
                                    .collect(Collectors.toList());
                            map.put("baseCategory3", baseCategory3Map.get(categoryBucket.key()));
                            map.put("list", top6List);
                            return map;

                        }).collect(Collectors.toList());
                return list;
            }


        } catch (IOException e) {
            log.error("查询置顶3级分类下热度TOP6专辑列表失败{}",e);
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public void saveSuggestIndex(AlbumInfoIndex albumInfoIndex) {
        //1.构建索引库文档对象
        SuggestIndex suggestIndex = new SuggestIndex();
        suggestIndex.setId(albumInfoIndex.getId().toString());
        String albumTitle = albumInfoIndex.getAlbumTitle();
        suggestIndex.setTitle(albumTitle);
        suggestIndex.setKeyword(new Completion(new String[]{albumTitle}));
        //1.1 将汉字转为汉语拼音 jing dian liu sheng ji
        String albumTitlePinyin = PinyinUtil.getPinyin(albumTitle, "");
        suggestIndex.setKeywordPinyin(new Completion(new String[]{albumTitlePinyin}));
        //1.1 将汉字转为汉语拼音首字母
        String albumTitleFirstLetter = PinyinUtil.getFirstLetter(albumTitle, "");
        suggestIndex.setKeywordSequence(new Completion(new String[]{albumTitleFirstLetter}));

        //2.存入提词文档记录到提词索引库
        suggestIndexRepository.save(suggestIndex);
    }

    @Override
    public List<String> completeSuggest(String keyword) {
        try {
            //采用自动补全API 尝试分别查询 汉字、拼音、拼音首字母自动补全
            SearchResponse<SuggestIndex> suggestIndexSearchResponse = elasticsearchClient.search(
                    s -> s.index(SUGGEST_INDEX_NAME)
                            .suggest(
                                    s1 -> s1.suggesters("letter-suggest", fs -> fs.prefix(keyword).completion(c -> c.field("keywordSequence").size(10).skipDuplicates(true)))
                                            .suggesters("pinyin-suggest", s2 -> s2.prefix(keyword).completion(c -> c.field("keywordPinyin").size(10).skipDuplicates(true)))
                                            .suggesters("keyword-suggest", s2 -> s2.prefix(keyword).completion(c -> c.field("keyword").size(10).skipDuplicates(true)))
                            )
                    , SuggestIndex.class
            );

            //解析es自动补全结果，放入hashset去重
            HashSet<String> hashSet = new HashSet<>();
            hashSet.addAll(this.parseSuggestResult(suggestIndexSearchResponse, "letter-suggest"));
            hashSet.addAll(this.parseSuggestResult(suggestIndexSearchResponse, "pinyin-suggest"));
            hashSet.addAll(this.parseSuggestResult(suggestIndexSearchResponse, "keyword-suggest"));
            // TODO 如果自动返回补全集合长度，如果小于10个，采用全文检索补全到10个
            if (hashSet.size() < 10) {
                //2.2.1 根据用户录入字符进行全文检索
                SearchResponse<AlbumInfoIndex> matchSearchResponse = elasticsearchClient.search(
                        s -> s.index(INDEX_NAME)
                                .query(q -> q.match(m -> m.field("albumTitle").query(keyword)))
                                .size(10)
                        , AlbumInfoIndex.class
                );
                HitsMetadata<AlbumInfoIndex> hits = matchSearchResponse.hits();
                List<Hit<AlbumInfoIndex>> hitList = hits.hits();
                if (CollectionUtil.isNotEmpty(hitList)) {
                    for (Hit<AlbumInfoIndex> hit : hitList) {
                        AlbumInfoIndex source = hit.source();
                        //2.2.2 将检索到专辑标题内容加入到提词结果列表中
                        hashSet.add(source.getAlbumTitle());
                        if (hashSet.size() >= 10) {
                            break;
                        }
                    }
                }
            }

            //3.如果自动补全结果长度大于10个，截取10个返回
            if (hashSet.size() >= 10) {
                //如果提词结果列表中大于10截取前10个
                return new ArrayList<>(hashSet).subList(0, 10);
            } else {
                return new ArrayList<>(hashSet);
            }
        } catch (IOException e) {
            log.error("用户输入字符{}自动补全失败{}", keyword, e);
            throw new RuntimeException(e);
        }

    }

    @Override
    public Collection<String> parseSuggestResult(SearchResponse<SuggestIndex> suggestIndexSearchResponse, String s) {
        //根据自定义建议词参数名称获取结果列表
        List<String> list = new ArrayList<>();
        List<Suggestion<SuggestIndex>> suggestionList = suggestIndexSearchResponse.suggest().get(s);
        if (CollectionUtil.isNotEmpty(suggestionList)) {
            //遍历得到建议对象
            for (Suggestion<SuggestIndex> suggestIndexSuggestion : suggestionList) {
                for (CompletionSuggestOption<SuggestIndex> option : suggestIndexSuggestion.completion().options()) {
                    SuggestIndex suggestIndex = option.source();
                    list.add(suggestIndex.getTitle());
                }
            }
        }
        return list;
    }

    /**
     * 更新不同分类不同排行TOP20数据
     *
     * @return
     */
    @Override
    public void updateLatelyAlbumRanking() {
        try {
            //1.远程调用专辑服务获取所有1级分类获取一级分类ID列表
            List<BaseCategory1> baseCategory1List = albumFeignClient.getAllCategory1().getData();

            //2.遍历所有一级分类ID-根据分类ID+排序方式+限制返回文档数量
            if (CollectionUtil.isNotEmpty(baseCategory1List)){
                List<Long> baseCategory1IdList = baseCategory1List.stream().map(BaseCategory1::getId).collect(Collectors.toList());
                for (Long baseCategory1Id : baseCategory1IdList) {
                    //声明当前分类hash结构Key
                    String redisKey = RedisConstant.RANKING_KEY_PREFIX + baseCategory1Id;
                    BoundHashOperations<String, String, List<AlbumInfoIndex>> hashOps = redisTemplate.boundHashOps(redisKey);
                    //处理某个一级分类排行数据，遍历5种不同排序字段
                    String[] rankingDimensionArray = {
                            "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum", "hotScore"};
                    for (String rankingDimension : rankingDimensionArray) {
                        //3.解析当前分类下当前排序方式命中TOP20专辑文档列表
                        SearchResponse<AlbumInfoIndex> albumInfoIndexSearchResponse = elasticsearchClient.search(
                                s -> s.index(INDEX_NAME)
                                        .query(q -> q.term(t -> t.field("category1Id").value(baseCategory1Id)))
                                        .sort(s1 -> s1.field(f -> f.field(rankingDimension).order(SortOrder.Desc)))
                                        .size(20)
                                        .source(s1 -> s1.filter(f -> f.includes("id", "albumTitle", "albumIntro", "coverUrl", "includeTrackCount", "playStatNum", "createTime", "payType")))
                                , AlbumInfoIndex.class
                        );
                        List<Hit<AlbumInfoIndex>> hitList = albumInfoIndexSearchResponse.hits().hits();
                        if (CollectionUtil.isNotEmpty(hitList)){
                            //3.1 遍历命中记录对象得到Hit对象中中_source（专辑对象）
                            List<AlbumInfoIndex> albumInfoIndexList = hitList.stream().map(hit -> hit.source()).collect(Collectors.toList());

                            //4.将不同分类不同维度的TOP20数据放入Redis
                            hashOps.put(rankingDimension, albumInfoIndexList);
                        }
                    }

                }
            }
        } catch (IOException e) {
            log.error("更新不同分类不同排行TOP20数据失败{}", e);
            throw new RuntimeException(e);
        }


    }

    @Override
    public List<AlbumInfoIndexVo> getRankingList(Long category1Id, String dimension) {
        String redisKey = RedisConstant.RANKING_KEY_PREFIX + category1Id;
        BoundHashOperations<String, String, List<AlbumInfoIndex>> hashOps = redisTemplate.boundHashOps(redisKey);
        List<AlbumInfoIndex> albumInfoIndices = hashOps.get(dimension);
        return albumInfoIndices.stream().map(albumInfoIndex -> BeanUtil.copyProperties(albumInfoIndex, AlbumInfoIndexVo.class)).collect(Collectors.toList());
    }

    @Override
    public void updateAlbumStat(TrackStatMqVo trackStatMqVo) {
        try {
            Long albumId = trackStatMqVo.getAlbumId();
            String incrementField = "";
            if(SystemConstant.TRACK_STAT_PLAY.equals(trackStatMqVo.getStatType())){
                incrementField = "playStatNum";

            }else if(SystemConstant.TRACK_STAT_COMMENT.equals(trackStatMqVo.getStatType())){
                incrementField = "commentStatNum";
            }
            String finalIncrementField = incrementField;
            elasticsearchClient.update(
                    u -> u.index(INDEX_NAME).id(albumId.toString())
                            .script(s -> s.inline(i -> i.lang("painless").source("ctx._source."+ finalIncrementField +" += params.increment").params(Map.of("increment", JsonData.of(trackStatMqVo.getCount())))))
                    , AlbumInfoIndex.class
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}